from os import write
from urllib import request
from urllib import parse
# 拼接URL地址


def get_url(word):
    url = 'http://www.baidu.com/s?{}'
    params = parse.urlencode({'wd': word})
    full_url = url.format(params)
    return full_url

# 向URL发送请求,保存为本地文件


def request_url(url, filename):
    # 重构请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0'
    }
    # 创建请求
    req = request.Request(url=url, headers=headers)
    # 获取响应
    res = request.urlopen(req)
    # 获取响应内容
    html = res.read().decode('utf-8')
    # 保存为本地文件
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(html)


# 主程序入口
if __name__ == '__main__':
    word = input('请输入搜索的内容：')
    url = get_url(word)
    filename = word+'.html'
    request_url(url, filename)
